package com.borened.common.core.util;

/**
 * 行政区划工具类
 *
 * @author: cch
 * @since: 2022/3/17
 */
public class RegionUtil {
    /**
     * 省/直辖市/自治区 级
     */
    public static final int PROVINCE_LEVEL = 2;
    /**
     * 市/辖区 级
     */
    public static final int CITY_LEVEL = 4;
    /**
     * 县/区 级
     */
    public static final int COUNTY_LEVEL = 6;
    /**
     * 乡镇/街道 级
     */
    public static final int TOWN_LEVEL = 9;
    /**
     * 村级/居委会 级
     */
    public static final int VILLAGE_LEVEL = 12;

    /**
     * 获取指定行政代码的上级代码
     * <p>
     * 使用预定的行政编码规律来截取字符串
     * </p>
     *
     * @param regionCode
     * @return
     */
    public static Long getParentRegion(Long regionCode) {
        if (regionCode == null) return null;
        String regionStr = String.valueOf(regionCode);
        int length = regionStr.length();
        switch (length) {
            case PROVINCE_LEVEL:
                return 0L;
            case CITY_LEVEL:
                return Long.valueOf(regionStr.substring(0, PROVINCE_LEVEL));
            case COUNTY_LEVEL:
                return Long.valueOf(regionStr.substring(0, CITY_LEVEL));
            case TOWN_LEVEL:
                return Long.valueOf(regionStr.substring(0, COUNTY_LEVEL));
            case VILLAGE_LEVEL:
                return Long.valueOf(regionStr.substring(0, TOWN_LEVEL));
            default:
                return null;
        }
    }

    /**
     * 当前用户是否有指定地区的数据权限
     *
     * @param regionCode 前端传递过来的编码值
     * @return
     */
    public static boolean hasPermission(Long regionCode) {
        Long selfRegionCode = JwtUtils.getRegionCode();
        String regionCodeStr = regionCode.toString();
        return regionCodeStr.indexOf(selfRegionCode.toString()) == 0;
    }

    public static void main(String[] args) {
    }
}
